<template>
  <div>
    <!--    v-if="uploadUrl"-->
    <el-upload
      :action="uploadUrl"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      accept=".jpg,.png,.jpeg,.JPG,.PNG,.JPEG"
      :http-request="
        (file) => {
          ossOtherSCJTUpload(file, 'imageUrl', '');
        }
      "
      name="file"
      :show-file-list="false"
      style="display: none"
      ref="upload"
    >
    </el-upload>

    <el-upload
      :action="uploadUrl"
      :before-upload="beforeAvatarUpload"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      accept=".mp4,.MP4"
      :http-request="
        (file) => {
          ossOtherSCJTUpload(file, 'videoUrl', '');
        }
      "
      name="file"
      :show-file-list="false"
      style="display: none"
      ref="uploadVideo"
    >
    </el-upload>
    <div class="editor" ref="editor" :style="styles">

    </div>
    <div class="div-toolbar">
      <el-color-picker
        v-model="selectedColor"
        @change="applyColor"
        style="margin-right:10px"
        show-alpha
        :predefine="predefineColors"
      ></el-color-picker>
      <el-input class="toolbarInput" type="text" v-model="fontSize" placeholder="请输入字体大小" @blur="setFontSize"></el-input>

      <el-input class="toolbarInput" type="text" v-model="dmWidth" placeholder="请输入弹幕宽度" @blur="setDmControl"></el-input>

      <el-input class="toolbarInput" type="text" v-model="dmHeight" placeholder="请输入弹幕高度" @blur="setDmControl"></el-input>
    </div>

  </div>
</template>

<script>
import Quill from "quill";

import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import "./css/font.css"

//quill编辑器的字体
var fonts = [
  "SimSun",
  "SimHei",
  "Microsoft-YaHei",
  "KaiTi",
  "FangSong",
  "Arial",
  "Times-New-Roman",
  "sans-serif",
];
// 自定义字号的大小
var sizes = ["10px", "11px", "12px", "13px", "14px", "15px", "16px", "18px", "20px", "22px", "26px", "28px", "30px"];
var Size = Quill.import("formats/size");
console.log('size', Size)
Size.whitelist = sizes;
var Font = Quill.import("formats/font");
Font.whitelist = fonts; //将字体加入到白名单
Quill.register(Size, true);

const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  // ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
  // [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  // [{ script: "sub" }, { script: "super" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  // [{ indent: "-1" }, { indent: "+1" }],
  // [{ size: sizes }], // 配置字号
  // [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  // [{ color: ["#000000", "#e60000", "#ff9900", "#ffff00", "#008a00", "#0066cc", "#9933ff", "#ffffff", "#facccc", "#ffebcc", "#ffffcc", "#cce8cc", "#cce0f5", "#ebd6ff", "#bbbbbb", "#f06666", "#ffc266", "#ffff66", "#66b966", "#66a3e0", "#c285ff", "#888888", "#a10000", "#b26b00", "#b2b200", "#006100", "#0047b2", "#6b24b2", "#444444", "#5c0000", "#663d00", "#666600", "#003700", "#002966", "#3d1466", 'custom-color']}, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{ font: fonts }], //显示字体选择
  [{ align: [] }], // 对齐方式-----[{ align: [] }]
  // ["clean"], // 清除文本格式-----['clean']
  // ['link', 'image', 'video'], // 链接、图片、视频-----
];

import {target, website} from "@/utils/config";
// import OSS from "ali-oss";
import format from "@/utils/format";
import * as service from "./service";


export default {
  name: "Editor",
  props: {
    /* 编辑器的内容 */
    value: {
      type: String,
      default: "",
    },
    /* 高度 */
    height: {
      type: Number,
      default: null,
    },
    /* 最小高度 */
    minHeight: {
      type: Number,
      default: null,
    },
    /* 只读 */
    readOnly: {
      type: Boolean,
      default: false,
    },
    /* 上传地址 */
    uploadUrl: {
      type: String,
      default: process.env.VUE_APP_BASE_API + "/system/file/upload",
    },
  },
  data() {
    return {
      selectedColor:'#000',
      predefineColors:["#000000", "#e60000", "#ff9900", "#ffff00", "#008a00", "#0066cc", "#9933ff", "#ffffff", "#facccc", "#ffebcc", "#ffffcc", "#cce8cc", "#cce0f5", "#ebd6ff", "#bbbbbb", "#f06666", "#ffc266", "#ffff66", "#66b966", "#66a3e0", "#c285ff", "#888888", "#a10000", "#b26b00", "#b2b200", "#006100", "#0047b2", "#6b24b2", "#444444", "#5c0000", "#663d00", "#666600", "#003700", "#002966", "#3d1466"],
      headers: {
        Authorization: window.localStorage.getItem(`token-${target}`),
      },
      fontSize: 14,
      Quill: null,
      currentValue: "",
      dmWidth: '120',
      dmHeight: '20',
      options: {
        theme: "snow",
        bounds: document.body,
        debug: "warn",
        modules: {
          // 工具栏配置
          // toolbar: [...toolbarOptions, [{handlers:{color:this.showColorPickerHandler}}]],
          toolbar:{
            container:toolbarOptions,
            handlers: {
              'direction': direction => {
                const isRTL = direction.value === 'rtl';
                const selection = quill.getSelection();
                this.Quill.formatText(selection, 'direction', isRTL ? 'rtl' : 'ltr');
              }
            }
          }
        },
        placeholder: "请输入内容",
        readOnly: this.readOnly,
        client: {},
      },
    };
  },
  computed: {
    styles() {
      let style = {};
      if (this.minHeight) {
        style.minHeight = `${this.minHeight}px`;
      }
      if (this.height) {
        style.height = `${this.height}px`;
      }
      return style;
    },
  },
  watch: {
    value: {
      handler(val) {
        if (val !== this.currentValue) {
          this.currentValue = val === null ? "" : val;
          if (this.Quill) {
            this.Quill.pasteHTML(this.currentValue);
          }
        }
      },
      immediate: true,
    },
  },
  mounted() {
    // const OSS = require("ali-oss");
    // this.client = new OSS({
    //   region: 'oss-cn-guangzhou',
    //   accessKeyId: 'LTAI5tNryQ3jq1BrBgT1N3NP',
    //   accessKeySecret: '8V63aooLcATW7SdQxAcpOVKQDxBgrL',
    //   bucket: 'zhenxiaohuiyi'
    // });
    this.init();
  },
  beforeDestroy() {
    this.Quill = null;
  },
  methods: {
    applyColor(color) {
      console.log('color', color)
      // const contentDom = document.querySelector('.ql-editor p')
      // contentDom.style.setProperty('color', color)
      this.Quill.format('color', color)
    },
    setEditWidthOrHeight(width=0, height=0) {
      console.log('设置 width ---', width, height)
      if(width > 0) {
        this.dmWidth = width
      }
      if(height > 0) {
        this.dmHeight = height
      }

      this.setDmControl()
    },
    setDmControl() {
      const contentDom = document.querySelector('.ql-editor p')
      contentDom.style.setProperty('width', `${this.dmWidth}px`)
      contentDom.style.setProperty('height', `${this.dmHeight}px`)
      this.$emit('setDmControl', {
        width: this.dmWidth,
        height: this.dmHeight
      })
    },
    setFontSize(fontSize=0) {
        const contentDom = document.querySelector('.ql-editor p')
      if(fontSize > 0) {
        this.fontSize = fontSize
      }
        contentDom.style.setProperty('font-size', `${this.fontSize}px`)
        // this.Quill.format('size', this.fontSize + 'px')
    },
    beforeAvatarUpload() {
      this.$emit("uploadBefore");
      return true;
    },
    init() {
      const editor = this.$refs.editor;
      this.Quill = new Quill(editor, this.options);
      // 如果设置了上传地址则自定义图片上传事件
      console.log("this.uploadUrl ---", this.uploadUrl);
      if (this.uploadUrl) {
        let toolbar = this.Quill.getModule("toolbar");
        toolbar.addHandler("image", (value) => {
          this.uploadType = "image";
          if (value) {
            this.$refs.upload.$children[0].$refs.input.click();
          } else {
            this.quill.format("image", false);
          }
        });
        toolbar.addHandler("video", (value) => {
          this.uploadType = "video";
          if (value) {
            this.$refs.upload.$children[0].$refs.input.click();
          } else {
            this.quill.format("video", false);
          }
        });
      }

      let toolbar = this.Quill.getModule("toolbar");
      toolbar.addHandler("video", (value) => {
        this.uploadType = "video";
        if (value) {
          this.$refs.uploadVideo.$children[0].$refs.input.click();
        } else {
          this.quill.format("video", false);
        }
      });

      this.Quill.pasteHTML(this.currentValue);
      this.Quill.on("text-change", (delta, oldDelta, source) => {
        let html = this.$refs.editor.children[0].innerHTML;
        if (html === "<p><br></p>") {
          html = "";
        }
        const text = this.Quill.getText();
        const quill = this.Quill;
        this.currentValue = html;
        this.$emit("input", html);
        this.$emit("on-change", { html, text, quill });
      });
      this.Quill.on("text-change", (delta, oldDelta, source) => {
        this.$emit("on-text-change", delta, oldDelta, source);
      });
      this.Quill.on("selection-change", (range, oldRange, source) => {
        this.$emit("on-selection-change", range, oldRange, source);
      });
      this.Quill.on("editor-change", (eventName, ...args) => {
        this.$emit("on-editor-change", eventName, ...args);
      });
      this.$nextTick(()=> {
        const contentDom = document.querySelector('.ql-editor p')
        contentDom.style.setProperty('width', `${this.dmWidth}px`)
        contentDom.style.setProperty('height', `${this.dmHeight}px`)
        this.setDmControl()
      })
    },
    async imageOssUploadMethods(file) {
      const fileType = file.type.split("/")[1];
      const uploadUrl = `upload/${format(
        new Date().getTime(),
        "YYYY-MM"
      )}/${new Date().getTime()}.${fileType}`;
      // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
      // 您可以通过自定义文件名（例如exampleobject.txt）或目录（例如exampledir/exampleobject.txt）的形式，实现将文件上传到当前Bucket或Bucket中的指定目录。
      let result = {};

      if (fileType === "pdf") {
        result = await this.client.multipartUpload(uploadUrl, file, {
          progress: (p, checkpoint, res) => {
            // checkpoint参数用于记录上传进度，断点续传上传时将记录的checkpoint参数传入即可。浏览器重启后无法直接继续上传，您需要手动触发上传操作。
            this.tempCheckpoint = checkpoint;
          },
          parallel: 4,
          // 设置分片大小。默认值为1 MB，最小值为100 KB。
          partSize: 1024 * 1024,
          mime: "application/x-pcx",
        });
      } else {
        result = await this.client.multipartUpload(uploadUrl, file, {
          progress: (p, checkpoint, res) => {
            // checkpoint参数用于记录上传进度，断点续传上传时将记录的checkpoint参数传入即可。浏览器重启后无法直接继续上传，您需要手动触发上传操作。
            this.tempCheckpoint = checkpoint;
          },
          parallel: 4,
          // 设置分片大小。默认值为1 MB，最小值为100 KB。
          partSize: 1024 * 1024,
          mime: "text/plain",
        });
      }
      this.$message.success("上传成功");
      return result;
    },
    ossOtherSCJTUpload(file, type, arrIndex) {
      // 获取富文本组件实例
      let quill = this.Quill;
      const files = file.file;
      this.isLoading = true;
      this.imageOssUploadMethods(files).then((result) => {
        service.accessFile(result.name).then((resChild) => {
          this.isLoading = false;
          if (type === "videoUrl") {
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // 插入图片  res.url为服务器返回的图片地址

            quill.insertEmbed(length, "video", resChild.data);
            // 调整光标到最后
            quill.setSelection(length + 1);
            this.$emit("uploadComplete");
          } else {
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // 插入图片  res.url为服务器返回的图片地址
            quill.insertEmbed(length, "image", resChild.data);
            // 调整光标到最后
            quill.setSelection(length + 1);
          }
        });
      });
    },
    handleUploadSuccess(res, file) {
      console.log("图片上传 ---", res);
      // 获取富文本组件实例
      let quill = this.Quill;
      // 如果上传成功
      if (res.code == 200) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.url为服务器返回的图片地址
        quill.insertEmbed(length, "image", website + res.data[0]);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        this.$message.error("图片插入失败");
      }
      this.$emit("uploadComplete");
    },
    handleUploadError() {
      this.$message.error("图片插入失败");
    },
  },
};
</script>

<style>
.editor,
.ql-toolbar {
  white-space: pre-wrap !important;
  line-height: normal !important;
}
.quill-img {
  display: none;
}
.ql-snow .ql-tooltip[data-mode="link"]::before {
  content: "请输入链接地址:";
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0px;
  content: "保存";
  padding-right: 0px;
}

.ql-snow .ql-tooltip[data-mode="video"]::before {
  content: "请输入视频地址:";
}

.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: "14px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
  content: "10px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
  content: "18px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
  content: "32px";
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: "文本";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: "标题1";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: "标题2";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: "标题3";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: "标题4";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: "标题5";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: "标题6";
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: "标准字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
  content: "衬线字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
  content: "等宽字体";
}
.ql-editor p{
  outline: 1px dashed #d6d6d6;
}
</style>

<style scoped>
.div-toolbar{
  position: absolute;
  top: 4px;
  left: 343px;
  display: flex;
}

.ql-color .ql-picker-options [data-value='custom-color'] {
  background: none !important;
  width: 100% !important;
  height: 20px !important;
  text-align: center;
}
.ql-color .ql-picker-options [data-value='custom-color']:before {
  content: 'Custom Color';
}
.ql-color .ql-picker-options [data-value='custom-color']:hover {
  border-color: transparent !important;
}
.toolbarInput{
  margin-right: 10px;
  width: 130px;
}
</style>
